<script setup>
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { onMounted } from 'vue';

const router = useRouter();
const authStore = useAuthStore();
const emit = defineEmits(['toggle-sidebar']);

const toggleSidebar = () => {
  emit('toggle-sidebar');
};

const handleLogout = async () => {
  await authStore.logout();
  router.push('/login');
};

// 组件挂载时恢复用户信息
onMounted(() => {
  authStore.recoverUserInfo();
});
</script>

<template>
  <header class="header">
    <div class="header-left">
      <button class="toggle-btn" @click="toggleSidebar">
        <el-icon><Menu /></el-icon>
      </button>
      <div class="logo">轻客管家</div>
    </div>
    <div class="header-right">
      <div class="user-info">
            <el-dropdown>
              <span class="user-name">
                <div class="avatar-container" v-if="authStore.userInfo.image">
                  <img :src="authStore.userInfo.image" class="user-avatar" alt="用户头像" />
                </div>
                <el-avatar v-else size="small" icon="User"></el-avatar>
                {{ authStore.userInfo.name || '未登录' }}
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleLogout">退出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
    </div>
  </header>
</template>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  color: #606266;
  margin-right: 20px;
  padding: 5px;
}

.toggle-btn:hover {
  color: #409EFF;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
      display: flex;
      align-items: center;
    }

    .user-name {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 20px;
    }

    .avatar-container {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 8px;
    }

    .user-avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-name .el-avatar {
      margin-right: 8px;
    }
</style>